package org.leon.interceptor;


import org.leon.controller.User;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by Administrator on 2017/4/27.
 */
public class AuthorizationInterceptor implements HandlerInterceptor {

    private static final String[] IGNORE_URI = {"/loginForm", "/login"};

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("AuthorizationInterceptor.preHandle");
        boolean flag = false;
        String servletPath = request.getServletPath();
        for(String s : IGNORE_URI){
            if(servletPath.contains(s)){
                flag = true;
                break;
            }
        }

        if(!flag){
            User user = (User) request.getSession().getAttribute("user");
            if(user == null){
                request.setAttribute("message", "请登录");
                request.getRequestDispatcher("loginForm").forward(request,response);
            }else{
                flag = true; // let go
            }
        }
        return flag;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
        System.out.println("AuthorizationInterceptor.postHandle");
    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
        System.out.println("AuthorizationInterceptor.afterCompletion");
    }
}
